#include "Sprite.h"
#include "common.h"

Sprite::Sprite (Dim _x, Dim _y, AnimationFilm* film): 
	x(_x), y(_y), currFilm(film), isVisible(true), flip_h(false), flip_v(false), step(NULL)
{ 
	frameNo = currFilm->GetTotalFrames(); 
	SetFrame(0);
}

void Sprite::SetFrame(byte i) {	
	if (i != frameNo) {
	    //assert(i < currFilm->GetTotalFrames());
		if(i >= currFilm->GetTotalFrames()) //another stupid fix...
			i = 0;
	    frameBox = currFilm->GetFrameBox(frameNo = i);
	}
}

byte Sprite::GetFrame (void) const { return frameNo; }

Rect Sprite::GetRect(void) const { 
	Rect bbox = currFilm->GetFrameBox(frameNo); 
	return Rect(x, y, SCALE*bbox.w, SCALE*bbox.h);
}

void Sprite::SetAnimationFilm(AnimationFilm *animF) {
	currFilm = animF;
	frameNo = animF->GetTotalFrames();
	SetFrame(0);
};

void Sprite::SetVisibility (bool v) { isVisible = v; }
    
bool Sprite::IsVisible (void) const { return isVisible; }

bool Sprite::CollisionCheck (Sprite* s) {
	int x1, y1, x2, y2, x3, y3, x4, y4;
	Rect b1, b2;
	b1 = s->GetRect();
	x1 = b1.x;
	y1 = b1.y;
	x2 = x1+b1.w;
	y2 = y1+b1.h;
	b2 = this->GetRect();
	x3 = b2.x;
	y3 = b2.y;
	x4 = x3+b2.w;
	y4 = y3+b2.h;
	//printf("[(%d,%d),(%d,%d)], [(%d,%d),(%d,%d)]\n", x1, y1, x2, y2, x3, y3, x4, y4);
	if((!(x2 < x3) && !(x1 > x4)) && (!(y2 < y3) && !(y1 > y4))) {
		CollisionAction(s);
		return true;
	}
	return false;
}

void Sprite::Display(const Rect& da) {
	currFilm->DisplayFrame(Point(x, y), frameNo, flip_h, flip_v);
	//al_draw_bitmap_region(currFilm->GetBitmap(), frameBox.x, frameBox.y, frameBox.w, frameBox.h, da.x, da.y, 0);
}

void Sprite::Move(int x, int y) {
	this->x += x;
	this->y += y;
}
